<template>
  <el-dialog
    title="转派"
    :visible="visible"
    class="dialog-class1 dialogStyle"
    @open="getFlowAttr"
    width="560px"
    :destroy-on-close="true"
    @close="resetForm"
  >
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="90px"
      v-loading="loading"
    >
      <el-form-item label="转派环节" prop="transpondLink">
        <el-select
          v-model="ruleForm.transpondLink"
          @change="getUserTree"
          placeholder="请选择"
        >
          <el-option
            v-for="item in selectDatas.transpondLinkList"
            :key="item.value"
            :label="item.linkName"
            :value="item.linkId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="处理人"
        class="redeploy-select select-user"
        prop="userList"
      >
        <tree-select
          v-model="ruleForm.userList"
          :allUserTreeData="allUserTreeData"
          :userTreeData="userTreeData"
          node-key="id"
          default-expand-all
          show-checkbox
          ref="treeSelect"
          :config="{ label: 'userName', value: 'userId' }"
          :isShowAllBtn="isShowAllBtn"
          :isShowAllInfo.sync="isShowAllInfo"
          :nextLinkInfo="
            this.selectDatas.transpondLinkList.find(
              (item) => item.curLink == this.ruleForm.transpondLink
            )
          "
        />
      </el-form-item>
      <div class="position-info">
        <editUsefulWord
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></editUsefulWord>
      </div>
      <el-form-item label="转派说明" class="small tip" prop="desc">
        <el-input
          type="textarea"
          v-model="ruleForm.desc"
          placeholder="请输入"
          size="small"
          maxlength="200"
        ></el-input>
      </el-form-item>
      <el-form-item v-show="isShowUsefulWord">
        <useful-word
          style="margin-top: -19px"
          :desc.sync="ruleForm.desc"
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></useful-word>
      </el-form-item>
      <el-form-item>
        <FormItemIconTipLabel slot="label" />
        <EventFileUpload v-model="ruleForm.orderFileDTOList" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="submitForm"
        :loading="btnLoading"
        style="margin-right: 10px"
        >确 定</el-button
      >
      <el-button @click="resetForm">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getUserTree } from "@/api/modules/eventManagement/eventDispatch";
import {
  queryReassignLink,
  reassignment,
} from "@/api/modules/eventManagement/redeploy.js";
import TreeSelect from "@/components/TreeSelect";
import { $getUrlParam } from "@/utils/public";
import UsefulWord from "@/views/pages/eventManagement/eventDialog/usefulWord";
import editUsefulWord from "@/views/pages/eventManagement/eventDialog/editUsefulWord";
import EventFileUpload from "../components/EventFileUpload";
import FormItemIconTipLabel from "../components/FormItemIconTipLabel";
export default {
  name: "redeployDialog",
  components: {
    TreeSelect,
    UsefulWord,
    editUsefulWord,
    EventFileUpload,
    FormItemIconTipLabel,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    orderData: {
      type: Object,
      default: () => {},
    },
    // 处置环节转派
    isDealStep: Boolean,
  },
  data() {
    return {
      allUserTreeData: [],
      ruleForm: {
        transpondLink: "",
        userList: "",
        desc: "",
      },
      userTreeData: [],
      loading: false,
      appVerCode: this.$store.getters.userInfo.appVerCode,
      industryCode: this.$store.getters.userInfo.industryCode,
      selectDatas: {
        transpondLinkList: [],
        nameList: [],
      },
      rules: {
        transpondLink: [
          {
            required: true,
            message: "请选择流转环节",
            trigger: ["blur", "change"],
          },
        ],
        userList: [
          {
            required: true,
            message: "请选择人员",
            trigger: ["blur", "change"],
          },
        ],
        desc: [
          {
            min: 0,
            max: 200,
            message: "字数请控制在200字符以内",
            trigger: "blur",
          },
        ],
      },
      isTenantAdmin: this.$store.getters.userInfo.isTenantAdmin, // 1 租户管理员
      isShowAllBtn: true /** 是否显示全部处理人按钮 */,
      isShowAllInfo: false, // 是否显示全部处理人
      isShowUsefulWord: false, // 是否显示常用语列表
      btnLoading: false,
    };
  },
  methods: {
    resetForm() {
      this.$emit("update:visible", false);
      this.ruleForm = {
        transpondLink: "",
        userList: "",
        desc: "",
      };
      this.isShowAllBtn = false; /** 是否显示全部处理人按钮 */
      this.isShowAllInfo = false; // 是否显示全部处理人
      this.isShowUsefulWord = false; // 是否显示常用语列表
      this.userTreeData = [];
    },
    // 字段转换
    transferTreeData(list) {
      return list.map((node) => {
        const { nodeId, ...rest } = node;
        let nodeName = node.userName || node.nodeName;
        const obj = {
          id: nodeId,
          label: nodeName,

          ...rest,
        };
        if (node.children) {
          return {
            ...obj,
            children: this.transferTreeData(node.children),
          };
        }
        return obj;
      });
    },
    getUserTree(linkParam) {
      const selectLinkData = this.selectDatas.transpondLinkList.filter(
        (item) => item.linkId === linkParam
      );
      this.isShowAllBtn = !(
        selectLinkData[0].dataFilterPermiss === "0" &&
        selectLinkData[0].customAdmin === "1"
      );
      this.isShowAllInfo =
        selectLinkData[0].dataFilterPermiss === "0" && !this.isShowAllBtn;
      const params = {
        curLink: linkParam,
        tenantId: this.$store.getters.userInfo.tenantId
          ? this.$store.getters.userInfo.tenantId
          : this.orderData.tenantId,
        flowId: this.orderData.flowId,
        deviceCode: this.orderData.deviceCode,
        provinceId: this.orderData.provinceId,
        cityId: this.orderData.cityId,
        countyId: this.orderData.countyId,
        warningSource: this.orderData.warningSource,
        gridId: this.orderData.gridId,
        warningTypeId: this.orderData.warningTypeId,
      };
      this.loading = true;
      getUserTree(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.userTreeData = this.transferTreeData([res.data.sysPowerInfo]);
          this.allUserTreeData = this.transferTreeData([res.data.sysAllInfo]);
          this.userTreeData[0].root = 1;
          this.allUserTreeData[0].root = 1;
          this.$nextTick(() => {
            this.$refs.treeSelect.checkTreeChange();
          });
        }
      });

      // this.dataList = [];
      // this.generateList(this.userTreeData);
    },
    async getFlowAttr() {
      this.btnLoading = false;
      this.loading = false;
      const res = await queryReassignLink({
        alarmFlowId: this.orderData.flowId,
        curLink: this.orderData.linkId,
        templateId: this.orderData.flowTemplate,
        appVerCode: this.appVerCode,
        industryCode: this.industryCode,
      });
      if (res.code === 200) {
        this.selectDatas.transpondLinkList = res.data;
        if (this.selectDatas.transpondLinkList.length == 1) {
          this.ruleForm.transpondLink =
            this.selectDatas.transpondLinkList[0].linkId;
          this.getUserTree(this.ruleForm.transpondLink);
        }
      }
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let curData = this.selectDatas.transpondLinkList.filter(
            (item) => item.linkId == this.ruleForm.transpondLink
          )[0];
          let params = {
            alarmFlowId: curData.alarmFlowId, //告警流程id
            appVerCode: this.appVerCode,
            industryCode: this.industryCode,
            beforLink: this.orderData.linkId, // 转派前环节id
            flowTemplate: this.orderData.flowTemplate, // 流程模板id
            curLink: this.ruleForm.transpondLink, // 转派后环节id
            linkName: curData.linkName, // 转派后环节别名
            realLinkType: curData.realLinkType, //转派后的真实环节类型
            timeLimit: curData.timeLimit,
            warningOrderId: this.orderData.warningOrderId,
            processDTOList: this.ruleForm.userList.map((ele) => ({
              processId: ele.userId,
              processName: ele.userName,
            })),
            remark: this.ruleForm.desc,
            userType: curData.userType,
            msgNotifyType: curData.msgNotifyType, // 转派后消息通知类型
            flowLinkType: "1", // 0 正常流转  1 转派  2 回退
            enableAcceptanceMode: this.orderData.enableAcceptanceMode, // 当前事件受理状态（0：不开启 1：开启（待受理）2：已受理 3：受理完成）
            timeLimitAcceptance: curData.timeLimitAcceptance, // 下一环节受理时限
            attrId: curData.attrId, // 下一环节流程环节id
            nextEnableAcceptanceMode: curData.enableAcceptanceMode, // 下一环节受理状态
            devicePitch: this.orderData.devicePitch, // 俯仰角
            alarmReason: this.orderData.alarmReason, // 告警原因
            deviceHorizontal: this.orderData.deviceHorizontal, // 水平角
          };
          // 如果是处置环节，附件处理同处理和处理回退。
          if (this.isDealStep) {
            params.processOrderVOList = [
              { processImgList: this.ruleForm.orderFileDTOList },
            ];
          } else {
            params.orderFileDTOList = this.ruleForm.orderFileDTOList; // 附件
          }
          if (this.orderData.updateAddress) {
            params.address = this.orderData.address;
            params.longitude = this.orderData.longitude;
            params.latitude = this.orderData.latitude;
            params.gridId = this.orderData.gridId;
            params.gridName = this.orderData.gridName;
            params.horiAzimuthAngle = this.orderData.horiAzimuthAngle;
            params.checkGridFlag = "1"; // 是否修改网格员  1 是  0 否
          } else {
            params.checkGridFlag = "0";
          }
          params.cityId = this.orderData.cityId;
          params.countyId = this.orderData.countyId;
          params.provinceId = this.orderData.provinceId;
          params.warningTypeId = this.orderData.warningTypeId;
          this.btnLoading = true;
          reassignment(params).then((res) => {
            this.btnLoading = false;
            let msgId = {
              id: this.orderData.warningOrderId,
              status: this.orderData.orderStatus,
            };
            this.$store.dispatch("closeSocketMsg", msgId);
            if (res.code == 200) {
              let userId = this.$store.getters.userInfo.userId;
              if (
                (Array.isArray(this.ruleForm.userList) &&
                  this.ruleForm.userList.find(
                    (item) => item.userId == userId
                  )) ||
                this.isTenantAdmin == "1"
              ) {
                // 有下一环节处理权限就自动打开下一环节
                this.$store.dispatch("tagsView/delView", this.$route);
                this.refreshSelectedTag(this.$route, params.realLinkType);
                $message.success("转派成功");
              } else {
                this.onSuccess();
              }
              this.resetForm();
            }
          });
        }
      });
    },
    onSuccess() {
      const url =
        $getUrlParam("pageType") === "false"
          ? "/eventManagement"
          : "/eventManagement/myEvent";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push(url);
    },
    refreshSelectedTag(view, realLinkType) {
      location.reload();
    },
    replaceParamVal(oUrl, paramName, replaceWith) {
      var re = eval("/(" + paramName + "=)([^&]*)/gi");
      var nUrl = oUrl.replace(re, paramName + "=" + replaceWith);
      return nUrl;
    },
  },
};
</script>

<style scoped lang="scss">
/deep/.el-dialog > .el-dialog__body {
  padding: 20px 60px 0;
}
/deep/textarea {
  resize: none;
}
/deep/.tip .el-form-item__error {
  padding-top: 12px;
}
/deep/ .el-form-item__error {
  position: relative;
}
/deep/.select-user .el-form-item__error {
  position: absolute;
  top: 35px;
  left: 5px;
}
.position-info {
  margin-top: -10px;
  padding-right: 5px;
  margin-bottom: 5px;
}
/deep/.redeploy-select .el-select__tags-text {
  overflow: hidden;
  text-overflow: ellipsis;
}
/deep/ .el-select__tags {
  overflow: auto;
  .el-tag.el-tag--info {
    max-width: 80%;
  }
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 4px;
  }
  /deep/ .el-dialog__header {
    padding: 12px;
  }
  /deep/ .el-dialog__footer {
    padding: 12px;
  }
  /deep/ .el-form-item--small.el-form-item {
    margin-bottom: 12px;
  }
  /deep/ .el-form-item .el-form-item__label {
    padding-right: 9px;
  }
  /deep/ .el-textarea__inner {
    height: 60px;
  }
}
</style>
